package com.china.springServer.service.impl;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.omg.CORBA.ServiceDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import java.util.Collection;

/**
 * @fileName: ZookeeperWatcher
 * @author: LmR
 * @createDate: 2023/10/21 21:52
 * @Desc:
 */
// 注释注解，关闭监听功能
//@Service
public class ZookeeperServerWatcher implements ApplicationRunner {

    @Autowired
    private CuratorFramework curatorClient;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        ServiceDiscovery<ServiceDetail> serviceDiscovery = ServiceDiscoveryBuilder.builder(ServiceDetail.class)
                .client(curatorClient)
                .basePath("myServer")
                .build();
        serviceDiscovery.start();

        while (true) {
            Collection<ServiceInstance<ServiceDetail>> services = serviceDiscovery.queryForInstances("server01");
            for (ServiceInstance<ServiceDetail> service : services) {
                System.out.println("监听服务注册: " + service.getAddress() + ":" + service.getPort());
            }
            Thread.sleep(3000);
        }
    }
}
